<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
use Exception;
use App\Models\ShopOrderAddress;
use App\Models\ShopSeckillGoods;
use App\Models\ShopGoodsStock;
class Order {
    /*
     *  商品列表
     */
    private $goods_list;
    /*
    *  订单信息
    */
    private $order_info;
    /*
    *  用户ID
    */
	private $uid;
    /*
    *  用户信息
    */
	private $user_info;
    /*
    *  地址信息
    */
	private $address_id;
    /*
    *  订单描述
    */
	private $remark;
    /*
    *  订单信息
    */
	private $order_sn;
    /*
    *  店铺ID
    */
    private $store_id;
    /*
    *  订单金额
    */
    private $order_amount;

    public function __construct($order_info=array(),$goods_list=array())
    {

        if(!$goods_list){
            echo '失败';
        }
        $this->address_id = $order_info['address_id'];
        $this->remark = $order_info['remark'];
        $this->uid = $order_info['uid'];
        $this->user_info = ClientUser::where(['id'=>$this->uid])->first();
        $this->goods_list = $goods_list;
        unset($order_info['address_id']);
        unset($order_info['remark']);
        $this->order_info=$order_info;
    }


    //创建订单
    public function createOrder(){

        $order = DB::transaction(function () {
            $order_info =$this->order_info;
            $goods_list =$this->goods_list;

            $order_info['user_name']=$this->user_info->realname?$this->user_info->realname:$this->user_info->username;
            $order_info['user_mobile']=$this->user_info->mobile;
            //创建订单号
            if($order_info['order_type']==1){
                //秒杀下单
                $goods_info = ShopSeckillGoods::buyStatus($goods_list[0]['goods_id']);

                $order_info ['store_id'] = 1;
                $order_info ['store_name'] =  $store_detail= ShopStore::getStoreDetailById(1)->store_name;
                $order_info ['order_amount'] = $goods_info->goods_price;
                $order_info ['goods_amount'] = $goods_info->goods_price;
                $order_info ['express_amount'] = 0;

            }else if($order_info['order_type']==2){
                $goods_info = ShopGroupGoods::getGoodsDetail($goods_list[0]['goods_id']);
                $order_info ['store_id'] = 1;
                $order_info ['store_name'] = $store_detail= ShopStore::getStoreDetailById(1)->store_name;
                $order_info ['order_amount'] = bcmul($goods_info->goods_price,$goods_list[0]['goods_number'],2);
                $order_info ['goods_amount'] = $goods_info->goods_price;
                $order_info ['express_amount'] = 0;
            }else{
                //普通商品取第一个商品去获得店铺信息

                $store_info = DB::table('shop_goods')->select('store.id as store_id','store.store_name')->leftJoin('shop_store as store','store.id','=','shop_goods.store_id')->where(['shop_goods.id'=>$goods_list[0]['goods_id']])->first();
                $order_info ['store_id'] = $store_info->store_id;
                $order_info ['store_name'] = $store_info->store_name;
                $this->store_id = $store_info->store_id;
                //订单金额计算
                $order_info ['express_amount'] = $store_info->shipping_amount;
                $order_info ['order_amount'] = 0;
                foreach ($goods_list as $key=>$val){
                    $goods_info = ShopGoods::getGoodsDetail($val['goods_id']);
                    $order_info ['order_amount'] = bcadd ( $order_info['order_amount'],bcmul($goods_info->goods_price,$val['goods_number'],2),2);
                }
                $order_info ['goods_amount'] = $order_info ['order_amount'];
                $order_info ['order_amount'] = bcadd($order_info ['order_amount'],$order_info['express_amount'],2);
                $order_info ['express_amount'] = 0;
                if($order_info['order_type']==4){
                    $order_info['status']=2;
                }
            }
            $order_info ['order_sn'] = self::createOrderSN();

            Message::message_push($this->store_id,'new_order','您有一条新订单待发货，订单号：'.$order_info ['order_sn'].'请及时处理',$order_info ['order_sn'],1);

            $create=ShopOrder::create($order_info);
            if(!$create){
                throw new Exception('订单表生成失败');
            }
            $this->order_sn = $order_info['order_sn'];
            $this->order_amount = $order_info['order_amount'];
            $this->store_id = $order_info['store_id'];

            self::createOrderAddress();
            self::createOrderGoods();
            self::createOrderLog();
            self::createOrderPayment();
            self::createOrderSplit();
            self::updateGoodsNumber();
            $order['order_sn'] = $order_info['order_sn'];
            $order['order_amount'] = $order_info['order_amount'];
            $order['order_type'] = $order_info['order_type'];
            return $order;

        });
        return $order;
    }

    //生成订单号
    private static function createOrderSN(){
        $order_sn=DB::select("select seq() as order_sn")['0']->order_sn;
        return $order_sn;
    }

    //更新库存表
    private function updateGoodsNumber(){
        $goods_list = $this->goods_list;
        foreach ($goods_list as $key=>$val) {
            $update = Log::addGoodsStock($val['goods_id'],$val['goods_type'],$this->uid,$val['goods_number']);

            if(!$update){
                throw new Exception('更新商品库存失败');
            }
        }
        return true;
    }
    //更新销量表

    //创建订单商品地址表
    private function createOrderAddress(){
        $address_id = $this->address_id;
        $user_address = ClientUserAddress::where(['uid'=>$this->uid,'id'=>$address_id])->first();

        if(!$this->order_sn){
            throw new Exception('订单号错误');
        }
        if(!$user_address){
            throw new Exception('地址参数错误');
        }
        $house = House::where(['house_id'=>$user_address->house_id])->first();

        if(!$house){
            throw new Exception('找不到房屋');
        }

        $order_address_info = array(
            'order_sn' =>$this->order_sn,
            'address_id'=>$this->address_id,
            'uid'=>$this->uid,
            'store_id'=>$this->store_id,
            'village_id'=>$house->village_id,
            'house_id'=>$user_address->house_id,
            'mobile'=>$user_address->mobile,
            'name'=>$user_address->realname,
            'express_type'=>1,
            'express_id'=>1,
            'express_name'=>'',
            'express_mobile'=>'',
            'address'=>$user_address->address,
            'remark'=>$this->remark
        );

        $create=ShopOrderAddress::create($order_address_info)->id;

        if(!$create){
            throw new Exception('订单地址表生成失败');
        }
    }

    //创建订单商品表
    private function createOrderGoods(){
        $goods_list = $this->goods_list;
        foreach ($goods_list as $key=>$val){
            if($val['goods_type']==1){
                $goods_info =ShopSeckillGoods::getGoodsDetail($val['goods_id']);
            }else if($val['goods_type']==2){
                $goods_info =ShopGroupGoods::getGoodsDetail($val['goods_id']);
            }else{
                $goods_info =ShopGoods::getGoodsDetail($val['goods_id']);
            }
			
            $order_goods_list[$key]=array(
                'uid'=>$this->uid,
                'store_id'=>$this->store_id,
                'order_sn'=>$this->order_sn,
                'goods_id'=>$val['goods_id'],
                'goods_name'=>$goods_info->goods_name,
                'goods_type'=>$val['goods_type'],
                'market_price'=>$goods_info->market_price,
                'goods_price'=>$goods_info->goods_price,
                'goods_image'=>$goods_info->goods_image,
                'goods_spec'=>$goods_info->goods_spec,
                'goods_number'=>$val['goods_number'],
                'created_at'=>date('Y-m-d H:i:s'),
                'updated_at'=>date('Y-m-d H:i:s'),
            );
        }
        $create=ShopOrderGoods::insert($order_goods_list);

        if(!$create){
            throw new Exception('订单商品表生成失败');
        }
    }

    //创建订单日志表
    private function createOrderLog(){
        $details = '用户'.$this->user_info->username.'在'.date('Y-m-d H:i:s').'下单'.$this->order_sn;
        $system_name = 'system';
        $create=ShopOrderLog::createOrderLog($this->uid,$this->order_sn,$details,$system_name);

        if(!$create){
            throw new Exception('订单日志表生成失败');
        }
    }

    //创建支付表
    private function createOrderPayment(){
        $order_payment_info = array(
            'uid'=>$this->uid,
            'store_id'=>$this->store_id,
            'order_sn'=>$this->order_sn,
            'pay_status'=>0,
            'order_amount'=>$this->order_amount,
            'pay_amount'=>$this->order_amount,
            'balance_amount'=>0
        );
        $create=ShopOrderPayment::create($order_payment_info)->id;
        if(!$create){
            throw new Exception('订单支付表生成失败');
        }
    }

    //创建订单分成表
    private function createOrderSplit(){
        $company_proportion = Config::key('company_proportion')->value('value'); //物业分成比例
        $platform_proportion = Config::key('platform_proportion')->value('value'); //平台分成比例暂时为0

        $village_id = ShopStore::getVillageIdByStore($this->store_id);
        if(!$village_id){
            //平台自营
            $split_uid=0;
            $store_amount = $this->order_amount;
            $platform_amount = $terrace_amount=0;
        }else {
            $terrace_amount = bcdiv(floor(bcmul($this->order_amount,$company_proportion,2)),100); //分成金额
            $platform_amount = bcdiv(floor(bcmul($this->order_amount,$platform_proportion,2)),100); //平台分成金额
            $store_amount = bcsub(bcsub($this->order_amount,$terrace_amount,2),$platform_amount,2);
            $split_uid = ClientUserRelationship::where(['village_id' => $village_id])->value('uid');
        }
        $order_split_info=array(
            'order_sn'=>$this->order_sn,
            'uid'=>$this->uid,
            'store_id'=>$this->store_id,
            'split_uid'=>$split_uid,
            'order_amount'=>$this->order_amount,
            'refund_amount'=>0,
            'store_amount'=>$store_amount,
            'platform_amount'=>$platform_amount,
            'terrace_amount'=>$terrace_amount,
            'status'=>0,
        );

        $create=ShopOrderSplit::create($order_split_info)->id;
        if(!$create){
            throw new Exception('订单结算表生成失败');
        }
    }
}